package com.zc.inkdemo;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.dianju.showpdf.DJContentView;
import com.dianju.showpdf.PageMode;
import com.zc.inkdemo.utils.ClfUtil;
import com.zc.inkdemo.utils.CommonUtil;
import com.zc.inkdemo.views.CalendarView;
import com.zc.inkdemo.views.ColorPickerView;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by LIBERTY on 2017/11/20.
 */

public class OpenFileActivity extends AppCompatActivity {

    private static final String SDPATH = Constant.PROJECT_PATH;//"/mnt/sdcard/dianju/";
    private String filePath = "";
    private int index = -1;
    String sealPath = SDPATH + "djtest.sel";
    String pfxPath = SDPATH + "123456.pfx";
    String pfxPwd = "123456";

    //private static int r = 255, g = 0, b = 0;
    //private static int s = 5;
    private LinearLayout contentLayout;
    private DJContentView contentView;
    private boolean isListener = true;
    private Context context;
    private Button btnBrowse, btnPublicSign, btnAddSeal, btnRevoke, btnSave, btnEraser, btnCheckSeal;
    private List userInfos = new ArrayList();
    private int currUser = 0;//当前用户
    private ListView userList;
    private String[] data;
    private LinearLayout userInfoLayout;
    private ArrayAdapter<String> adapter;
    private static String backgroudColor = "#A9A9A9";
    private String mPhotoPath = Constant.PROJECT_PATH + "1.jpg";
    private MyHandler handler = new MyHandler();
    int[] leftTopPoint = null;//节点左上角坐标，里面放置的是文档坐标(非屏幕坐标)
    int[] rightBottomPoint = null;//节点右下角坐标，里面放置的是文档坐标(非屏幕坐标)
    int tempColor;
    String autoHandleType = "";//用来表示在AUTO_HANDLE状态下进行的是遮盖还是手写操作

    /**
     * 外接编辑框-start
     */
    InputMethodManager imm;
    private LinearLayout editLayout;
    private EditText editArea;
    private Button btnCancel;
    private Button btnOk;
    /** 外接编辑框-end */

    /**
     * 外接日历-start
     */
    private LinearLayout calendarLayout;
    private CalendarView calendar;
    private ImageView calendarLeft;
    private ImageView calendarRight;
    private TextView calendarTxt;
    private TextView nowTime;
    private TextView btnCalendarClose;
    SimpleDateFormat format;
    private static final int calendarSize = 350;//弹出日历大小
    /** 外接日历-end */

    /**
     * 获取日历适当的尺寸
     */
    float[] getPropSize(float x, float y, float width, float height) {
        float[] res = new float[3];
        if (width > calendarSize) {
            res[0] = x + ((width - calendarSize) / 2);

        } else {
            res[0] = x;
        }
        res[1] = y + height;
        res[2] = calendarSize;
        return res;
    }

    class MyHandler extends Handler {
        public void handleMessage(Message msg) {// 处理消息
            switch (msg.what) {
                case 10001:// 盖章完成后返回的消息
                    // b_gaizhang.setBackgroundColor(0);
                    break;
            }
        }
    }

    /**
     * 初始化外接控件
     */
    void initExternalView() {
        //初始化编辑框
        editLayout = (LinearLayout) this.findViewById(R.id.editLayout);
        editArea = (EditText) this.findViewById(R.id.editArea);
        btnCancel = (Button) this.findViewById(R.id.btn_cancel);
        btnOk = (Button) this.findViewById(R.id.btn_ok);
        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        /** 文字-确定按钮 */
        btnOk.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (contentView.getCurrAction() == DJContentView.OperType.EDITTEXT && contentView.canEditText == true) {//编辑
                    contentView.setValue(contentView.currNodeName, editArea.getText().toString());
                    contentView.freshPDF();
                } else if (contentView.getCurrAction() == DJContentView.OperType.TEXT) {//批注(插入)
                    String nodename = getRandName(DJContentView.NodeType.Head.EDIT_TEXT_EX);
                    int res = contentView.insertNote(nodename, DJContentView.NodeType.EDIT_TEXT_EX, contentView.getClickPage(), contentView.getClickNodeX(), contentView.getClickNodeY(), 49000 - contentView.getClickNodeX(), 1000);
                    contentView.setValue(nodename, ":PROP:FACENAME:仿宋_GB2312");
                    contentView.setValue(nodename, ":PROP:FONTSIZE:16");
                    contentView.setValue(nodename, ":PROP:FONTBOLD:1");
                    res = contentView.setValue(nodename, editArea.getText().toString());
                }
                editArea.setText("");
                editLayout.setVisibility(View.GONE);
                imm.hideSoftInputFromWindow(editArea.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                contentView.freshPDF();
                //编辑完毕需解锁屏幕
                contentView.unLockScreen();
            }
        });
        /** 文字-取消按钮 */
        btnCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                editArea.setText("");
                editLayout.setVisibility(View.GONE);
                //imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                imm.hideSoftInputFromWindow(editArea.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                contentView.setCurrAction(1);
                //编辑完毕需解锁屏幕
                contentView.unLockScreen();
            }
        });

        //初始化日历
        format = new SimpleDateFormat("yyyy-MM-dd");
        this.calendarLayout = (LinearLayout) this.findViewById(R.id.calendarLayout);
        this.calendar = (CalendarView) this.findViewById(R.id.calendar);
        this.calendarLeft = (ImageView) this.findViewById(R.id.btnCalendarLeft);
        this.calendarRight = (ImageView) this.findViewById(R.id.btnCalendarRight);
        this.calendarTxt = (TextView) this.findViewById(R.id.calendarTxt);
        this.nowTime = (TextView) this.findViewById(R.id.now_time);
        this.btnCalendarClose = (TextView) this.findViewById(R.id.btnCalendarClose);
        calendar.setSelectMore(false); //单选
        /** 日历的点击事件 */
        calendar.setOnItemClickListener(new CalendarView.OnItemClickListener() {

            @Override
            public void OnItemClick(Date selectedStartDate, Date selectedEndDate, Date downDate) {
                if (calendar.isSelectMore()) {
                    //Toast.makeText(getApplicationContext(), format.format(selectedStartDate)+"到"+format.format(selectedEndDate), Toast.LENGTH_SHORT).show();
                } else {
                    if (contentView != null) {
                        SimpleDateFormat simFormat = new SimpleDateFormat("yyyyMMdd");
                        String time = simFormat.format(downDate);
                        contentView.setValue(contentView.currNodeName, time);
                        contentView.freshPDF();
                        calendarLayout.setVisibility(View.GONE);
                        //编辑完毕需解锁屏幕
                        contentView.unLockScreen();
                    }
                }
            }
        });

        calendarLeft.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //点击上一月 同样返回年月
                String leftYearAndmonth = calendar.clickLeftMonth();
                String[] ya = leftYearAndmonth.split("-");
                calendarTxt.setText(ya[0] + "年" + ya[1] + "月");
            }
        });

        calendarRight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //点击下一月
                String rightYearAndmonth = calendar.clickRightMonth();
                String[] ya = rightYearAndmonth.split("-");
                calendarTxt.setText(ya[0] + "年" + ya[1] + "月");
            }
        });

        btnCalendarClose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                calendarLayout.setVisibility(View.GONE);
                //编辑完毕需解锁屏幕
                contentView.unLockScreen();
            }
        });

        Calendar now = Calendar.getInstance();
        int nowYear = now.get(Calendar.YEAR);
        int nowMonth = now.get(Calendar.MONTH) + 1;
        int nowDay = now.get(Calendar.DAY_OF_MONTH);
        String nowDate = "今天：" + nowYear + "/" + nowMonth + "/" + nowDay;
        nowTime.setText(nowDate);
    }

    /**
     * 外接事件
     */
    void externalEvent(MotionEvent event) {
        if ((!contentView.isLockScreen()) && ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP)) {
            /** 获取坐标 */
            int x = contentView.getClickNodeX();
            int y = contentView.getClickNodeY();
            int width = contentView.getClickNodeWidth();
            int height = contentView.getClickNodeHeight();
            if ((contentView.getCurrAction() == DJContentView.OperType.EDITTEXT) && (!TextUtils.isEmpty(contentView.currNodeName)) && (!contentView.isUseDefaultPopView())) {//编辑功能(文字框、日历)【jar内部有实现】
                if (contentView.isDateNode(contentView.currNodeName)) {//日历
                    String nodeValue = contentView.getValueEx(contentView.currNodeName, 2, "", 1, "");
                    Date date = null;
                    if (TextUtils.isEmpty(nodeValue)) {
                        date = new Date();
                    } else {
                        try {
                            date = format.parse(nodeValue);
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    calendar.setCalendarData(date);
                    String[] time = calendar.getYearAndmonth().split("-");
                    calendarTxt.setText(time[0] + "年" + time[1] + "月");
                    float[] res = getPropSize(x, y, width, height);//对坐标进行计算，获取适当的显示位置
                    calendarLayout.setX(res[0]);
                    calendarLayout.setY(res[1]);
                    calendarLayout.setLayoutParams(new RelativeLayout.LayoutParams((int) res[2], (int) res[2]));
                    calendarLayout.setVisibility(View.VISIBLE);
                    //弹框需锁屏
                    contentView.lockScreen();
                } else if (contentView.isEditBoxNode(contentView.currNodeName)) {//文字编辑框
                    String userName = ClfUtil.getSPString(context, Constant.LOGIN_NAME, Constant.LOGIN_NAME_DEFAULT);
                    String content = contentView.getValueEx(contentView.currNodeName, 2, userName, 0, "");
                    /** 获取点击文本控件距离父容器左边顶部的距离(页面坐标) */
                    editLayout.setX(x);
                    editLayout.setY(y);
                    editLayout.setLayoutParams(new RelativeLayout.LayoutParams(width, LinearLayout.LayoutParams.WRAP_CONTENT));
                    editArea.setLayoutParams(new LinearLayout.LayoutParams(width, height));
                    editArea.setText(content);
                    editLayout.setVisibility(View.VISIBLE);
                    imm.showSoftInput(editArea, InputMethodManager.HIDE_NOT_ALWAYS);
                    //弹编辑框需锁屏
                    contentView.lockScreen();
                } else {
                }
            } else if (contentView.getCurrAction() == DJContentView.OperType.TEXT && (!contentView.isUseDefaultPopView())) {//插入文字编辑框【jar内部有实现】
                editLayout.setX(200);
                editLayout.setY(200);
                editArea.setText("");
                editLayout.setVisibility(View.VISIBLE);
                editArea.requestFocus();
                imm.showSoftInput(editArea, InputMethodManager.HIDE_NOT_ALWAYS);
                //弹编辑框需锁屏
                contentView.lockScreen();
            } else if (contentView.getCurrAction() == DJContentView.OperType.AUTO_HANDLE) {//供外部扩展的功能(jar内部不去实现)
                if (Constant.AUTO_HANDLE_COVER.equals(autoHandleType)) {/** 创建遮挡区域 */
                    String nodename = getRandName(DJContentView.NodeType.Head.COVER);
                    int mWidth = width;
                    int mHeight = height;
                    if (width < 1000) mWidth = 1000;
                    if (mHeight < 500) mHeight = 500;
                    int res = contentView.insertNoteByWH(nodename, DJContentView.NodeType.COVER, contentView.getClickPage(), x, y, mWidth, mHeight);
                    contentView.setValue(nodename, ":PROP:ZHEDANGMODE:1");    //添加遮盖曾属性
                    int color = Color.parseColor("#E0E5E4");
                    if (color < 0) {
                        color = color & 0xffffff;
                    }
                    contentView.setValue(nodename, ":PROP:BACKCOLOR:" + color);//设置遮层曾颜色
                    contentView.setCurrAction(DJContentView.OperType.EDITTEXT);//遮挡区域进入编辑状态(可拖动状态)
                    contentView.freshPDF();
                } else if (Constant.SIGN_AUTO.equals(autoHandleType)) {/** 创建手写区域,不可移动 */
                    /** 弹出手写框 */
//                    Intent intent = new Intent();
//                    intent.setClass(OpenFileActivity.this, PopWriteActivity1.class);
//                    intent.putExtra("type", Constant.SIGN_AUTO);
//                    startActivityForResult(intent, Constant.RequestCode.SIGN_AUTO);
                    //弹编辑框需锁屏
                    contentView.lockScreen();
                } else if (Constant.SIGN_AUTO_PFX.equals(autoHandleType)) {//签字带证书(盖手写章)
                    /** 弹出手写框 */
//                    Intent intent = new Intent();
//                    intent.setClass(OpenFileActivity.this, PopWriteActivity1.class);
//                    intent.putExtra("type", Constant.SIGN_AUTO_PFX);
//                    startActivityForResult(intent, Constant.RequestCode.SIGN_AUTO_PFX);
                    //弹编辑框需锁屏
                    contentView.lockScreen();
                } else if (Constant.AUTO_HANDLE_VOICE.equals(autoHandleType)) {//语音签批
//                    Intent intent = new Intent();
//                    intent.putExtra("filePath", Constant.VOICE_PATH);
//                    intent.setClass(OpenFileActivity.this, SoundRecorderActivity.class);
//                    startActivityForResult(intent, Constant.RequestCode.AUTO_HANDLE_VOICE);
                    //弹编辑框需锁屏
                    contentView.lockScreen();
                } else if (Constant.AUTO_PHOTO.equals(autoHandleType)) {//插入图片
//                    Intent intent = new Intent(OpenFileActivity.this, MyFileManager.class);
//                    startActivityForResult(intent, Constant.RequestCode.AUTO_PHOTO);
//                    //弹编辑框需锁屏
//                    contentView.lockScreen();
                }
            } else {
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        setContentView(R.layout.openfile);
        context = this;
        Intent intent = getIntent();
        String action = intent.getAction();
        String tempFilePath = "";
        String type = "";
        if (intent.ACTION_VIEW.equals(action)) {
            Uri uri = (Uri) intent.getData();
            tempFilePath = uri.getPath();
            filePath = tempFilePath;
        } else {
            filePath = extras.getString("filePath1");
            index = extras.getInt("index");
            type = extras.getString("type");
        }
        initExternalView();
        //editLayout = (LinearLayout) this.findViewById(R.id.editLayout);
        btnBrowse = (Button) this.findViewById(R.id.browse);//浏览
        btnPublicSign = (Button) this.findViewById(R.id.public_sign);//签批
        btnAddSeal = (Button) this.findViewById(R.id.addSeal);//盖章
        btnRevoke = (Button) this.findViewById(R.id.revoke);//撤销
        btnSave = (Button) this.findViewById(R.id.save);//保存
        btnEraser = (Button) this.findViewById(R.id.eraser);//另存
        btnCheckSeal = (Button) this.findViewById(R.id.checkSeal);//验章

        userList = (ListView) findViewById(R.id.userList);
        userInfoLayout = (LinearLayout) findViewById(R.id.userInfoLayout);
        if (filePath.endsWith(".aip")) {//aip文件无法验章
            btnAddSeal.setVisibility(View.GONE);
            btnCheckSeal.setVisibility(View.GONE);
        }
        switch (index) {
            case 0:
                userInfos.add(new String[]{"签发人", "qfr", "0", "7945", "10313", "11980", "6000"});
                userInfos.add(new String[]{"会签人", "hqr", "0", "25662", "10313", "11980", "6000"});
                break;
            case 1:
                userInfos.add(new String[]{"申请人", "sqr", "0", "30290", "38557", "7053", "3517"});
                userInfos.add(new String[]{"受理人", "slr", "0", "30290", "44212", "7053", "3517"});
                break;
            case 2:
                userInfos.add(new String[]{"甲方", "jf", "1", "10579", "10775", "8000", "4000"});
                userInfos.add(new String[]{"乙方", "yf", "1", "31864", "10775", "8000", "4000"});
                break;
            case 3:
                userInfos.add(new String[]{"被保险人", "bbxr", "0", "24615", "30964", "8449", "4152"});
                break;
            case 4:
                userInfos.add(new String[]{"抄表人", "cbr", "0", "13602", "35129", "6400", "3200"});
                userInfos.add(new String[]{"业主", "yz", "0", "29282", "35129", "6400", "3200"});
                break;
            case 5:
                userInfos.add(new String[]{"申请人", "sqr", "0", "40000", "30000", "9000", "5000"});
                break;
            case 6:
                userInfos.add(new String[]{"总经理", "zjl", "0", "7620", "31400", "8824", "4412"});
                userInfos.add(new String[]{"项目经理", "xmjl", "0", "22549", "31400", "8824", "4412"});
                userInfos.add(new String[]{"审核人", "shr", "0", "37745", "31400", "8824", "4412"});
                break;
            case 7:
                userInfos.add(new String[]{"当事人", "dsr", "0", "12909", "35307", "6675", "3339"});
                userInfos.add(new String[]{"交通警察", "jtjc", "0", "12909", "39181", "6675", "3339"});
                break;
            case 8:
                userInfos.add(new String[]{"经办人", "jbr", "0", "35516", "28673", "12000", "4096"});
                userInfos.add(new String[]{"负责人", "fzr", "0", "35516", "38691", "12000", "4096"});
                break;

        }
        //System.out.println("filePath:"+filePath);
        contentLayout = (LinearLayout) this.findViewById(R.id.contentLayout1);
        /** 进行绘制之前，先创建好画布，进行画笔的定义 */
        contentLayout.getViewTreeObserver().addOnPreDrawListener(
                new ViewTreeObserver.OnPreDrawListener() {
                    public boolean onPreDraw() {
                        if (isListener) {
                            isListener = false;
                            contentView = new DJContentView(context);
                            /** 获取翻页模式 */
                            String pagemode = ClfUtil.getSPString(context, Constant.PAGE_MODE, Constant.PAGE_MODE_DEFAULT);
                            if ("0".equals(pagemode)) {
                                contentView.setPageMode(PageMode.SinglePage);
                            }
                            String setFonts = ClfUtil.getSPString(context, Constant.SET_FONTS, Constant.SET_FONTS_DEFAULT);
                            if ("1".equals(setFonts)) {
                                int fontRes = contentView.setValue("SET_FONTFILES_PATH", Constant.FONTS_PATH);//设置使用外部的字体文件
                                Log.d("chenlongfei", "fontRes=" + fontRes);
                            }
                            int openRes = 0;
                            //设置不能擦除旧的手写内容(全屏写)
                            contentView.setValue("DEL_FORCETYPE_VALUE", "8192");
                            if (filePath.endsWith(".pdf")) {
                                openRes = contentView.openFile(filePath);
                            } else {//aip ,ofd
                                openRes = contentView.openTempFile(filePath);
                            }
                            Log.d("chenlongfei", "openRes=" + openRes);
                            String userName = ClfUtil.getSPString(context, Constant.LOGIN_NAME, Constant.LOGIN_NAME_DEFAULT);
                            String res = CommonUtil.login(context, contentView, userName);
                            if (!"ok".equals(res)) {
                                Toast.makeText(context, res, Toast.LENGTH_LONG).show();
                            }
                            contentView.setOnTouchListener(new View.OnTouchListener() {
                                @Override
                                public boolean onTouch(View view, MotionEvent event) {
                                    contentView.onTouchEvent(event);//保持contentview原有的放大缩小功能还在
                                    //外接编辑控件(文字录入、日历)
                                    externalEvent(event);
                                    return true;
                                }
                            });
                            contentLayout.addView(contentView);
                            contentView.setValue("ADD_FORCETYPE_VALUE6", "" + (6 * 16));
                            contentView.setValue("PREDEF_TIMEFORMAT", "256");
                            contentView.setAutoPlayVoice(true);//启用语音点击自动播放
                            /** 设置笔宽和颜色 */
                            int penWidth = ClfUtil.getSPInt(context, Constant.penWidth, Constant.DEFAULT_PEN_WIDTH);
                            int penColor = ClfUtil.getSPInt(context, Constant.penColor, Constant.DEFAULT_PEN_COLOR);
                            contentView.setPenAttr(penWidth, penColor);
                            /** 设置是否支持手写功能，该功能默认支持 */
                            String isHandWrite = ClfUtil.getSPString(context, Constant.isHandWrite, Constant.DEFAULT_HANDWRITE);
                            if (!"true".equals(isHandWrite)) {
                                contentView.setUseFingerWrite(false);
                            }
                            /** 使用外接编辑还是内置控件(默认使用外接控件) */
                            String isInternalControl = ClfUtil.getSPString(context, Constant.isInternalConrol, Constant.DEFAULT_INTERNAL_CONTROL);
                            if ("true".equals(isInternalControl)) {
                                contentView.setUseDefaultPopView(true);
                            }
                            String setSignSuffix = ClfUtil.getSPString(context, Constant.SET_SIGNSUFFIX, Constant.SET_SIGNSUFFIX_DEFAULT);
                            if ("1".equals(setSignSuffix)) {
                                contentView.setUserInfoEx(userName, 0, 7, Constant.SIGNSUFFIX_PIC);
                            }
                            //contentView.setValue("ADD_FORCETYPE_VALUE", "8192");
                        }
                        return true;
                    }
                });

        data = new String[userInfos.size()];
        for (int i = 0; i < userInfos.size(); i++) {
            String[] temp = (String[]) userInfos.get(i);
            data[i] = temp[0];
        }
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
        userList.setAdapter(adapter);
        /** 为用户列表添加点击事件 */
        userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                currUser = arg2;
                userInfoLayout.setVisibility(View.GONE);
            }
        });


        /** 为签批按钮添加点击事件 */
        btnPublicSign.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                contentView.setCurrAction(4);
            }
        });


        /** 浏览 */
        btnBrowse.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                contentView.setCurrAction(DJContentView.OperType.NONE);
            }
        });

        btnCheckSeal.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                /*contentView.setEditTextNote(editArea);
                contentView.setCurrAction(6);*/
                /** 验章 */
                List<Map<String, Object>> list = null;
                try {
                    list = contentView.getVerifyInfo();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (list.size() <= 0) {
                    Toast.makeText(context, "无印章", Toast.LENGTH_SHORT).show();
                    return;
                }
                boolean res = (Boolean) list.get(0).get("verifyRes");
                if (res) {
                    Toast.makeText(context, "印章有效", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "印章已无效", Toast.LENGTH_SHORT).show();
                }
                /*for(int i=0;i<list.size();i++) {
                    Map<String,Object> map = list.get(i);
					*//** 数字签名验证结果 *//*
                    Boolean verifyRes = (Boolean) map.get("verifyRes");
					*//** 证书信息 *//*
					X509Certificate certInfo = (X509Certificate) map.get("certInfo");
				}*/
            }
        });


        /** 为录音按钮添加点击事件 */
		/*b_luyin.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(OpenFileActivity.this,
						SoundRecorderActivity.class);
				startActivityForResult(intent, 3);
			}
		});*/
        btnSave.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                contentView.saveFile(filePath);
                contentView.disposeResource();
                contentView = null;
                finish();
            }
        });

        //擦除
        btnEraser.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                contentView.setCurrAction(DJContentView.OperType.ERASER);
            }
        });

        /** 为撤销按钮添加点击事件 */
        btnRevoke.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                contentView.undoAll(false);
            }
        });

        /** 为盖章添加点击事件 */
        btnAddSeal.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if (index == 0 || index == 1) {
                    sealPath = SDPATH + "sxg.sel";
                    String[] postionInfo = (String[]) userInfos.get(currUser);
                    int pageIdex = Integer.valueOf(postionInfo[2]);
                    int x = Integer.valueOf(postionInfo[3]);
                    int y = Integer.valueOf(postionInfo[4]);
                    int w = Integer.valueOf(postionInfo[5]);
                    int h = Integer.valueOf(postionInfo[6]);
                    contentView.addSealEX(sealPath, pfxPath, pfxPwd, 2, pageIdex, x + w / 2, y + h / 2);
                    //int b = contentView.addSeal(sealPath2, pfxPath, pfxPwd, 2);
                } else {
                    contentView.addSeal(sealPath, pfxPath, pfxPwd, 2);
                }
            }
        });

    }

    //设置颜色和笔宽弹出框
    public void showDialog() {
        View view = View.inflate(context, R.layout.setting, null);
        ColorPickerView colorPanel = (ColorPickerView) view.findViewById(R.id.color_panel);
        final RadioGroup group = (RadioGroup) view.findViewById(R.id.radioGroup);
        /** 初始化笔宽 */
        final SeekBar penWidthBar = (SeekBar) view.findViewById(R.id.penWidthBar);
        final TextView prePenWidth = (TextView) view.findViewById(R.id.pre_penWidth);
        int penWidth = ClfUtil.getSPInt(context, Constant.penWidth, Constant.DEFAULT_PEN_WIDTH);
        penWidthBar.setProgress(penWidth);
        prePenWidth.setText("" + penWidth);

        final TextView serialno = (TextView) view.findViewById(R.id.serialno);
        serialno.setText(contentView.getserialno());

        penWidthBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                prePenWidth.setText("" + progress);
            }
        });

        final TextView preColor = (TextView) view.findViewById(R.id.pre_color);
        /** preColor初始化颜色值 */
        int penColor = ClfUtil.getSPInt(context, Constant.penColor, Constant.DEFAULT_PEN_COLOR);
        preColor.setBackgroundColor(penColor);
        tempColor = penColor;

        /** 为颜色板添加监听事件 */
        colorPanel.setOnColorChangedListenner(new ColorPickerView.OnColorChangedListener() {

            //颜色移动的时候
            @Override
            public void onMoveColor(int r, int g, int b) {
                preColor.setBackgroundColor(Color.rgb(r, g, b));
                //penColor = ""+Color.rgb(r, g, b);
            }

            //手指抬起，选定颜色时
            @Override
            public void onColorChanged(int r, int g, int b) {
                preColor.setBackgroundColor(Color.rgb(r, g, b));
                tempColor = Color.rgb(r, g, b);
            }
        });

        /** 初始化手写 */
        String isHandWrite = ClfUtil.getSPString(context, Constant.isHandWrite, Constant.DEFAULT_HANDWRITE);
        if ("true".equals(isHandWrite)) {
            group.check(R.id.radioEnable);
        } else {
            group.check(R.id.radioDisable);
        }

        DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                /** 记录笔宽 */
                ClfUtil.addSP(context, Constant.penWidth, penWidthBar.getProgress());
                /** 记录颜色值，并设置颜色 */
                ClfUtil.addSP(context, Constant.penColor, tempColor);
                contentView.setPenAttr(penWidthBar.getProgress(), tempColor);

                /** 设置是否能够手写 */
                if (group.getCheckedRadioButtonId() == R.id.radioEnable) {
                    ClfUtil.addSP(context, Constant.isHandWrite, "true");
                    contentView.setUseFingerWrite(true);
                } else if (group.getCheckedRadioButtonId() == R.id.radioDisable) {
                    ClfUtil.addSP(context, Constant.isHandWrite, "false");
                    contentView.setUseFingerWrite(false);
                } else {
                }

            }
        };
        /** 弹出颜色板 */
        ClfUtil.popDialog(context, "", "确定", "取消", positiveListener, null, view);
    }

    public void showBaseDialog() {
        View view = View.inflate(context, R.layout.basesetting, null);
        final RadioGroup controlGroup = (RadioGroup) view.findViewById(R.id.controlGroup);
        final RadioGroup browseGroup = (RadioGroup) view.findViewById(R.id.browseGroup);
        /** 初始化签字设置 */
        String isMove = ClfUtil.getSPString(context, Constant.SIGN_ISMOVE, Constant.SIGN_MOVE_DEFAULT);
        String isBack = ClfUtil.getSPString(context, Constant.SIGN_ISBACK, Constant.SIGN_BACK_DEFAULT);
        String isTransparent = ClfUtil.getSPString(context, Constant.SIGN_ISTRANSPARENT, Constant.SIGN_TRANSPARENT_DEFAULT);
        final CheckBox isMoveCB = (CheckBox) view.findViewById(R.id.sign_move);
        final CheckBox isBackCB = (CheckBox) view.findViewById(R.id.sign_back);
        final CheckBox isTransparentCB = (CheckBox) view.findViewById(R.id.sign_transparent);
        if ("1".equals(isMove)) {
            isMoveCB.setChecked(true);
        } else {
            isMoveCB.setChecked(false);
        }
        if ("1".equals(isBack)) {
            isBackCB.setChecked(true);
        } else {
            isBackCB.setChecked(false);
        }
        if ("1".equals(isTransparent)) {
            isTransparentCB.setChecked(true);
        } else {
            isTransparentCB.setChecked(false);
        }

        /** 初始化控件设置(内置/外接) */
        String isInternalConrol = ClfUtil.getSPString(context, Constant.isInternalConrol, Constant.DEFAULT_INTERNAL_CONTROL);
        if ("true".equals(isInternalConrol)) {
            controlGroup.check(R.id.internalRadio);
        } else {
            controlGroup.check(R.id.externalRadio);
        }

        /** 初始化浏览模式 */
        String pageMode = ClfUtil.getSPString(context, Constant.PAGE_MODE, Constant.PAGE_MODE_DEFAULT);
        if ("0".equals(pageMode)) {
            browseGroup.check(R.id.landscapeRadio);
        } else {
            browseGroup.check(R.id.portraitRadio);
        }

        /** 初始化字体设置 */
        final CheckBox externalFonts = (CheckBox) view.findViewById(R.id.externalFonts);
        String setFonts = ClfUtil.getSPString(context, Constant.SET_FONTS, Constant.SET_FONTS_DEFAULT);
        if ("1".equals(setFonts)) {
            externalFonts.setChecked(true);
        } else {
            externalFonts.setChecked(false);
        }

        /** 初始化签名图片设置 */
        final CheckBox signSuffix = (CheckBox) view.findViewById(R.id.sign_suffix);
        String setSignSuffix = ClfUtil.getSPString(context, Constant.SET_SIGNSUFFIX, Constant.SET_SIGNSUFFIX_DEFAULT);
        if ("1".equals(setSignSuffix)) {
            signSuffix.setChecked(true);
        } else {
            signSuffix.setChecked(false);
        }

        DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                /** 设置使用内置控件还是外接控件*/
                if (controlGroup.getCheckedRadioButtonId() == R.id.internalRadio) {
                    ClfUtil.addSP(context, Constant.isInternalConrol, "true");
                    contentView.setUseDefaultPopView(true);
                } else if (controlGroup.getCheckedRadioButtonId() == R.id.externalRadio) {
                    ClfUtil.addSP(context, Constant.isInternalConrol, "false");
                    contentView.setUseDefaultPopView(false);
                } else {
                }

                /** 设置签字风格 */
                if (isMoveCB.isChecked()) {
                    ClfUtil.addSP(context, Constant.SIGN_ISMOVE, "1");
                } else {
                    ClfUtil.addSP(context, Constant.SIGN_ISMOVE, "0");
                }
                if (isBackCB.isChecked()) {
                    ClfUtil.addSP(context, Constant.SIGN_ISBACK, "1");
                } else {
                    ClfUtil.addSP(context, Constant.SIGN_ISBACK, "0");
                }
                if (isTransparentCB.isChecked()) {
                    ClfUtil.addSP(context, Constant.SIGN_ISTRANSPARENT, "1");
                } else {
                    ClfUtil.addSP(context, Constant.SIGN_ISTRANSPARENT, "0");
                }

                /** 设置翻页模式 */
                if (browseGroup.getCheckedRadioButtonId() == R.id.landscapeRadio) {
                    ClfUtil.addSP(context, Constant.PAGE_MODE, "0");
                    contentView.setPageMode(PageMode.SinglePage);
                } else if (browseGroup.getCheckedRadioButtonId() == R.id.portraitRadio) {
                    ClfUtil.addSP(context, Constant.PAGE_MODE, "1");
                    contentView.setPageMode(PageMode.MultiPage);
                } else {
                }

                /** 设置字体 */
                if (externalFonts.isChecked()) {//需要重新打开生效
                    ClfUtil.addSP(context, Constant.SET_FONTS, "1");
                } else {
                    ClfUtil.addSP(context, Constant.SET_FONTS, "0");
                }

                /** 设置签名图片 */
                if (signSuffix.isChecked()) {
                    ClfUtil.addSP(context, Constant.SET_SIGNSUFFIX, "1");
                    String userNameR = ClfUtil.getSPString(context, Constant.LOGIN_NAME, Constant.LOGIN_NAME_DEFAULT);
                    contentView.setUserInfoEx(userNameR, 0, 7, Constant.SIGNSUFFIX_PIC);
                } else {//取消需要重新打开才能生效
                    ClfUtil.addSP(context, Constant.SET_SIGNSUFFIX, "0");
                }
            }
        };
        /** 弹出基础设置面板 */
        ClfUtil.popDialog(context, "", "确定", "取消", positiveListener, null, view);
    }

    public void showAuthDialog() {
        View view = View.inflate(context, R.layout.authorizationsetting, null);
        //加载授权方式
        final RadioGroup authorizationGroup = (RadioGroup) view.findViewById(R.id.authorizationGroup);
        final EditText djCode = (EditText) view.findViewById(R.id.djCode);
        final TextView accountT = (TextView) view.findViewById(R.id.accountT);
        Button register = (Button) view.findViewById(R.id.register);
        final TextView errorTxt = (TextView) view.findViewById(R.id.errorTxt);
        final TextView verifyInstruction = (TextView) view.findViewById(R.id.verifyInstruction);
        final LinearLayout submitArea = (LinearLayout) view.findViewById(R.id.submitArea);
        final TextView verifyState = (TextView) view.findViewById(R.id.verifyState);
        String authType = ClfUtil.getSPString(context, Constant.AUTHORIZATION_TYPE, Constant.AUTHORIZATION_TYPE_DEFAULT);

        if ("1".equals(authType)) {//设备号授权
            authorizationGroup.check(R.id.imeiVerify);
            verifyInstruction.setText(Constant.AUTHORIZATION_IMEI_STR);
            String verifyLic = ClfUtil.getSPString(context, Constant.AUTHORIZATION_LIC, Constant.AUTHORIZATION_LIC_DEFAULT);
            djCode.setText(verifyLic);
            accountT.setText("授权码:");
            //submitArea.setVisibility(View.VISIBLE);

            //加载授权状态
            if (TextUtils.isEmpty(verifyLic)) {
                verifyState.setText("无授权");
            } else {
                int verifyRes = contentView.verifyLic(verifyLic);
                if (verifyRes == 1) {//授权成功
                    verifyState.setText("授权-有效");
                } else {//授权失败
                    verifyState.setText("授权-无效");
                }
            }
        } else if ("2".equals(authType)) {//账号授权
            authorizationGroup.check(R.id.accountVerify);
            verifyInstruction.setText(Constant.AUTHORIZATION_ACCOUNT_STR);
            accountT.setText("账    号:");
            //submitArea.setVisibility(View.VISIBLE);
            String account1 = ClfUtil.getSPString(context, Constant.AUTHORIZATION_ACCOUNT1, Constant.AUTHORIZATION_ACCOUNT1_DEFAULT);
            djCode.setText(account1);
            if (!TextUtils.isEmpty(account1)) {
                //加载授权状态
                try {
                    String verifyRes = contentView.getLicOnline("", account1);//从存储中读取授权(不填写地址，仅访问本地缓存授权，本地无授权返回验证失败)
                    if ("ok".equals(verifyRes)) {
                        verifyState.setText("授权-有效");
                    } else {
                        verifyState.setText("无授权code=" + verifyRes);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    verifyState.setText("调用异常");
                }
            } else {
                verifyState.setText("无授权");
            }
        } else if ("3".equals(authType)) {//二维码授权
            String account2 = ClfUtil.getSPString(context, Constant.AUTHORIZATION_ACCOUNT2, Constant.AUTHORIZATION_ACCOUNT2_DEFAULT);
            authorizationGroup.check(R.id.codeVerify);
            verifyInstruction.setText(Constant.AUTHORIZATION_CODE_STR);
            accountT.setText("账    号:");
            //register.setText("绑定");
            //submitArea.setVisibility(View.INVISIBLE);
            //加载授权状态
            if (!TextUtils.isEmpty(account2)) {
                int verifyRes = contentView.verifyLicById(account2);
                if (verifyRes == 1) {
                    verifyState.setText("授权-有效");
                } else {
                    verifyState.setText("无授权code=" + verifyRes);
                }
            } else {
                verifyState.setText("无授权");
            }
        }

        //加载imei
        TextView imeiET = (TextView) view.findViewById(R.id.imeiNo);
        String imeitxt = contentView.getserialno();
        imeiET.setText(imeitxt);

        //选项切换
        authorizationGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                if (checkedId == R.id.imeiVerify) {
                    verifyInstruction.setText(Constant.AUTHORIZATION_IMEI_STR);
                    //加载授权状态
                    String verifyLic = ClfUtil.getSPString(context, Constant.AUTHORIZATION_LIC, Constant.AUTHORIZATION_LIC_DEFAULT);
                    djCode.setText(verifyLic);
                    accountT.setText("授权码:");
                    if (TextUtils.isEmpty(verifyLic)) {
                        verifyState.setText("无授权");
                    } else {
                        int verifyRes = contentView.verifyLic(verifyLic);
                        if (verifyRes == 1) {//授权成功
                            verifyState.setText("授权-有效");
                        } else {//授权失败
                            verifyState.setText("授权-无效");
                        }
                    }
                    //submitArea.setVisibility(View.VISIBLE);
                } else if (checkedId == R.id.accountVerify) {
                    verifyInstruction.setText(Constant.AUTHORIZATION_ACCOUNT_STR);
                    String account1 = ClfUtil.getSPString(context, Constant.AUTHORIZATION_ACCOUNT1, Constant.AUTHORIZATION_ACCOUNT1_DEFAULT);
                    djCode.setText(account1);
                    accountT.setText("账    号:");
                    //加载授权状态
                    if (!TextUtils.isEmpty(account1)) {
                        try {
                            String verifyRes = contentView.getLicOnline("", account1);//从存储中读取授权(不填写地址，仅访问本地缓存授权，本地无授权返回验证失败)
                            if ("ok".equals(verifyRes)) {
                                verifyState.setText("授权-有效");
                            } else {
                                verifyState.setText("无授权");
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            verifyState.setText("调用异常");
                        }
                    }
                    //submitArea.setVisibility(View.VISIBLE);
                } else if (checkedId == R.id.codeVerify) {
                    String account2 = ClfUtil.getSPString(context, Constant.AUTHORIZATION_ACCOUNT2, Constant.AUTHORIZATION_ACCOUNT2_DEFAULT);
                    djCode.setText(account2);
                    accountT.setText("账    号:");
                    verifyInstruction.setText(Constant.AUTHORIZATION_CODE_STR);
                    //加载授权状态
                    if (!TextUtils.isEmpty(account2)) {
                        int verifyRes = contentView.verifyLicById(account2);
                        if (verifyRes == 1) {
                            verifyState.setText("授权-有效");
                        } else {
                            verifyState.setText("无授权");
                        }
                    }

                    //submitArea.setVisibility(View.INVISIBLE);
                }
                if (errorTxt.getVisibility() == View.VISIBLE) {
                    errorTxt.setVisibility(View.INVISIBLE);
                }
            }
        });

        //授权验证
        register.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //取授权码，验证是否授权通过
                String content = djCode.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    errorTxt.setTextColor(Color.RED);
                    errorTxt.setText("验证授权失败,授权码/账号不能为空!");
                    errorTxt.setVisibility(View.VISIBLE);
                    return;
                }
                if (authorizationGroup.getCheckedRadioButtonId() == R.id.imeiVerify) {//设备号授权
                    int verifyRes = contentView.verifyLic(content);
                    if (verifyRes == 1) {//授权成功
                        ClfUtil.addSP(context, Constant.AUTHORIZATION_LIC, content);//授权码模式，授权码需要自己存储
                        errorTxt.setTextColor(Color.GREEN);
                        errorTxt.setText("验证授权成功!授权码已存储至app！");
                        verifyState.setText("授权-有效");
                    } else {//授权失败
                        errorTxt.setTextColor(Color.RED);
                        errorTxt.setText("验证授权失败error=" + verifyRes);
                    }
                } else if (authorizationGroup.getCheckedRadioButtonId() == R.id.accountVerify) {//账号授权
                    try {
                        String verifyRes = contentView.getLicOnline(Constant.AUTHORIZATION_ADDRESS, content);
                        if ("ok".equals(verifyRes)) {//授权成功
                            ClfUtil.addSP(context, Constant.AUTHORIZATION_ACCOUNT1, content);//账号授权模式，账号需要自己存储
                            errorTxt.setTextColor(Color.GREEN);
                            errorTxt.setText("验证授权成功!账号已存储至app！");
                            verifyState.setText("授权-有效");
                        } else {//授权失败
                            errorTxt.setTextColor(Color.RED);
                            errorTxt.setText("验证授权失败error=" + verifyRes);
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        errorTxt.setText("验证授权失败error=" + e.getMessage());
                    }
                } else if (authorizationGroup.getCheckedRadioButtonId() == R.id.codeVerify) {//二维码授权
                    int verifyRes = contentView.verifyLicById(content);
                    if (verifyRes == 1) {
                        ClfUtil.addSP(context, Constant.AUTHORIZATION_ACCOUNT2, content);//二维码授权模式，账号需要自己存储
                        errorTxt.setTextColor(Color.GREEN);
                        errorTxt.setText("验证授权成功!账号已存储至app！");
                        verifyState.setText("授权-有效");
                    } else {
                        errorTxt.setTextColor(Color.RED);
                        errorTxt.setText("验证授权失败error=" + verifyRes);
                    }
                }
                errorTxt.setVisibility(View.VISIBLE);
            }
        });

        DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //首先验证授权是否通过
                if (authorizationGroup.getCheckedRadioButtonId() == R.id.imeiVerify) {
                    ClfUtil.addSP(context, Constant.AUTHORIZATION_TYPE, "1");
                } else if (authorizationGroup.getCheckedRadioButtonId() == R.id.accountVerify) {
                    ClfUtil.addSP(context, Constant.AUTHORIZATION_TYPE, "2");
                } else if (authorizationGroup.getCheckedRadioButtonId() == R.id.codeVerify) {
                    ClfUtil.addSP(context, Constant.AUTHORIZATION_TYPE, "3");
                }
            }
        };

        /** 弹出基础设置面板 */
        ClfUtil.popDialog(context, "", "确定", "取消", positiveListener, null, view);
    }

    /**
     * 切换用户
     */
    public void showUserDialog() {
        //LinearLayout conLayout = new LinearLayout(context);
        View view = View.inflate(context, R.layout.usersetting, null);
        //加载用户名
        final EditText userNameET = (EditText) view.findViewById(R.id.userName);
        String userNameR = ClfUtil.getSPString(context, Constant.LOGIN_NAME, Constant.LOGIN_NAME_DEFAULT);
        //HWSEALDEMO、HWSEALDEMO1、HWSEALDEMO2、HWSEALDEMO3是点聚默认的测试用户
        String userName = "HWSEALDEMO";
        if (!TextUtils.isEmpty(userNameR)) userName = userNameR;
        userNameET.setText(userName);
        //加载用户类型
        Spinner userType = (Spinner) view.findViewById(R.id.userType);
        if (userName.startsWith("HWSEALDEMO")) {
            userType.setSelection(0);//测试用户
        } else {
            userType.setSelection(1);//正式用户
        }
        //为spinner添加点击事件
        userType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    String userNameTemp = userNameET.getText().toString();
                    if (!userNameTemp.startsWith("HWSEALDEMO")) {
                        userNameET.setText("HWSEALDEMO");
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });
        //确定事件
        DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String userNameTemp = userNameET.getText().toString();
                if (TextUtils.isEmpty(userNameTemp)) {
                    Toast.makeText(context, "登陆失败,用户名不能为空！", Toast.LENGTH_LONG).show();
                } else {
                    ClfUtil.addSP(context, Constant.LOGIN_NAME, userNameTemp);
                    String res = CommonUtil.login(context, contentView, userNameTemp);
                    if ("ok".equals(res)) {
                        Toast.makeText(context, userNameTemp + ",登陆成功!", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, res, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        };
        /** 弹出基础设置面板 */
        ClfUtil.popDialog(context, "", "确定", "取消", positiveListener, null, view);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return false;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_settings:
                showDialog();
                break;
            case R.id.base_settings:
                showBaseDialog();
                break;
            case R.id.auth_settings:
                showAuthDialog();
                break;
            case R.id.menu_user:
                showUserDialog();
                break;
            case R.id.menu_about:
                Toast toast = Toast.makeText(OpenFileActivity.this, "XXXX有限公司\r\nwww.xxxx.cn", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                break;
            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    /*@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
         contentView.waitTogoback();//?????
         contentView.disposeResource();
         return super.onKeyDown(keyCode, event);
    }*/
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != Constant.RequestCode.PHOTO && data == null) {
            contentView.setCurrAction(DJContentView.OperType.NONE);
            contentView.unLockScreen();//屏幕解锁
            return;
        }
        switch (requestCode) {
            case Constant.RequestCode.SAVE_AS://另存
                if (resultCode == 1) {
                    String savePath = data.getStringExtra("savePath");
                    String fileName = data.getStringExtra("fileName");
                    ClfUtil.addSP(context, Constant.SAVE_PATH, savePath);
                    if (!TextUtils.isEmpty(fileName)) {
                        boolean res;
                        if (fileName.endsWith(".pdf")) {
                            res = ClfUtil.saveTo(contentView.getFile(), savePath + File.separator + fileName);
                        } else if (fileName.endsWith(".ofd")) {
                            res = ClfUtil.saveTo(contentView.getTempFile(), savePath + File.separator + fileName);
                        } else {
                            res = ClfUtil.saveTo(contentView.getTempFile(), savePath + File.separator + fileName);
                        }
                        String resInfo = "";
                        if (res) {
                            resInfo = "保存成功！";
                        } else {
                            resInfo = "保存失败！";
                        }
                        Toast.makeText(OpenFileActivity.this, resInfo, Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case Constant.RequestCode.SIGN_POSITION://弹出手写窗体返回
                if (resultCode == 1) {//确定按钮
                    String writeData = data.getStringExtra("writeData");
                    String png64Str = data.getStringExtra("getLastpic");
                    String[] postionInfo = (String[]) userInfos.get(currUser);
                    int pageIdex = Integer.valueOf(postionInfo[2]);
                    int x = Integer.valueOf(postionInfo[3]);
                    int y = Integer.valueOf(postionInfo[4]);
                    int w = Integer.valueOf(postionInfo[5]);
                    int h = Integer.valueOf(postionInfo[6]);
                    contentView.pasteNodesEx(writeData, pageIdex, w, h, x, y);
                    contentView.freshPDF();
                }
                break;
            case Constant.RequestCode.SIGN_AUTO://扩展的弹窗手写
                if (resultCode == 1) {//确定按钮
                    String writeData = data.getStringExtra("writeData");
                    String png64Str = data.getStringExtra("getLastpic");
                    if (!TextUtils.isEmpty(writeData)) {
                        String nodename = getRandName(DJContentView.NodeType.Head.HAND);
                        int mWidth = contentView.getClickNodeWidth();
                        int mHeight = contentView.getClickNodeHeight();
                        if (mWidth < 5000 && mHeight < 5000) {
                            mWidth = 5000;//(DJ文档宽高范围是0-50000)
                            mHeight = 3000;
                        }
                        int res = contentView.insertNoteByWH(nodename, DJContentView.NodeType.HAND, contentView.getClickPage(), contentView.getClickNodeX(), contentView.getClickNodeY(), mWidth, mHeight);
                        contentView.setValue(nodename, ":PROP:FREESIZE:2");
                        contentView.setValue(nodename, ":PROP:HWCHARFORMAT:100,300,300");
                        contentView.pasteNodesToArea(nodename, writeData);
                        //int penWidth = ClfUtil.getSPInt(context, Constant.penWidth, Constant.DEFAULT_PEN_WIDTH);
                        //int penColor = ClfUtil.getSPInt(context, Constant.penColor, Constant.DEFAULT_PEN_COLOR);
                        //contentView.setPenAttr(penWidth, penColor);
                        //Toast.makeText(OpenFileActivity.this, "设置笔宽和颜色penWidth="+penWidth, Toast.LENGTH_LONG).show();
                        //contentView.setValueEx(nodename, 44, 1, signDatas);
                        contentView.freshPDF();
                    }
                }
                contentView.unLockScreen();//屏幕解锁
                contentView.setCurrAction(DJContentView.OperType.NONE);
                break;
            case Constant.RequestCode.SIGN_AUTO_PFX://签字带证书
                if (resultCode == 1) {//确定按钮
                    File file = new File(Constant.PNG_PATH);
                    if (file.exists()) {
                        int x = contentView.getClickNodeX();
                        int y = contentView.getClickNodeY();
                        int width = contentView.getClickNodeWidth();
                        int height = contentView.getClickNodeHeight();
                        contentView.addHandSealEx(Constant.PNG_PATH, pfxPath, pfxPwd, 2, contentView.getClickPage(), x + width / 2, y + height / 2, 50);
                        contentView.freshPDF();
                    }
                }
                contentView.unLockScreen();//屏幕解锁
                contentView.setCurrAction(DJContentView.OperType.NONE);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (contentView != null) {
            contentView.saveFile("");
            contentView.disposeResource();
            contentView = null;
        }
        super.onDestroy();
    }

    //获取一个随机字符串
    String getRandName(String head) {
        Date d = new Date();
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String nodename = head + format.format(d);
        return nodename;
    }
}
